<template>
	<a-layout>
		<a-layout-header :class="classes.header" class="flx-ce-bet colorBgContainer">
			<Logo style="width: 200px;" :collapse="false" />
			<div :class="classes.rightControl">
				<!-- <a-dropdown  @select="handleViewSelect" :popup-max-height="false">
					<a-button class="borderRadius" :class="[classes.item, classes.viewBtn]" type="text">
						视图模式
						<icon-down />
					</a-button>
					<template #content>
						<a-doption v-for="item in viewData" :key="item.val" :value="item.val">
							<template #icon>
								<icon-check v-if="viewval === item.val" style="font-size: 16px; color: #1e6fff" />
							</template>
							<template #default>{{ item.text }}</template>
						</a-doption>
					</template>
				</a-dropdown> -->
				<!-- <a-button class="borderRadius" :class="[classes.item, classes.viewBtn]" type="text" @click="handleSass"> 轻文档Sass</a-button> -->
				<!-- <a-button class="borderRadius" :class="[classes.item, classes.viewBtn]" type="text" @click="handleDownload"> 下载</a-button> -->
				<a-select :style="{width: '230px', marginRight: '20px'}" placeholder="请选择" v-model="saveOption" v-if="zxcId">
					<a-option value="part" label="保存并同步至AI"></a-option>
					<a-option value="all" label="保存转换前后文件并同步至AI"></a-option>
   				</a-select>
				<a-button class="borderRadius" :class="[classes.item, classes.viewBtn]" type="text" @click="onImpoon"> 导入到知识库</a-button>
				<!-- <a-button class="borderRadius" :class="[classes.item, classes.viewBtn]" type="text" @click="handleSass"> 轻文档Sass</a-button> -->
				<!-- <a href="http://flowmix.turntip.cn/docx/price" target="_blank" :class="classes.item" class="pubCol">私有化部署</a>
				<a href="https://dooring.vip" target="_blank" :class="[classes.item, classes.hidable]" class="pubCol">更多产品</a>
				<a-popover title="扫码解锁更多黑科技">
					<template #content>
						<a-image src="https://cdn.dooring.cn/FlqY2Ji13zIMMzucQITvryG13m5j" :width="160" />
					</template>
					<a :class="[classes.item, classes.hidable]" class="pubCol">技术交流</a>
				</a-popover> -->
				<!-- <span :class="classes.item" class="pubCol" @click="handleToggleTheme">
					<icon-sun-fill :class="classes.colorWarningText" v-if="appStore.theme == 'light'" />
					<icon-moon-fill v-else />
				</span> -->
			</div>
		</a-layout-header>
		<el-dialog title="导入" v-model="dialog.visibleDialog" width="550px" :before-close="getClose" class="visible-dialog">
			<el-form  label-width="auto" style="max-width: 600px">
				<el-form-item label="文件名称" required>
					<el-input v-model="dialog.realName" placeholder="请输入文件名称"></el-input></el-form-item>
			</el-form>
			<div  v-loading="dialog.treeLoading">
			<el-tree
				v-if="!zxcId"
				ref="treeRestore"
				:data="dialog.treeRestoreList"
				:props="dialog.defaultProps"
				node-key="id"
				class="filter-tree"
				:lazy="true"
				:load="loadNode"
				:highlight-current="true"
				:default-expanded-keys="dialog.expandedKeys"
				:expand-on-click-node="false"
				@node-click="treeRestoreNodeClick"
			>
				<template #default="{ node, data }">
				<svg-icon :icon-class="node.expanded ? 'file-open' : 'file-close'"></svg-icon>
				<span>{{ node.label }}</span>
				</template>
			</el-tree>
			<div v-if="!zxcId" class="path">{{ $t('teamDist.restorePath') }} {{ dialog.treeRestorePathObj.path.replace(/\//g, '\\') }}</div>
			</div>
        <template #footer >
          <el-button @click="getClose">
            {{  $t('teamDist.close') }}
          </el-button>
          <el-button type="success" @click="getReset" > {{ $t('teamDist.reset') }} </el-button>
          <el-button @click="debounce_getComfirm"> {{ $t('commen.confirm') }} </el-button>
        </template>
		</el-dialog>
	</a-layout>
</template>

<script setup lang="ts">
import { Message } from "@arco-design/web-vue"
import { outputMdTest } from "../mdExport"
// api
import {
  apiTreeFileSelectTree,
  ApiPerSelectPersonalTree
} from '@/api/personDoc/personDocApi';
import { apiOcrToLibrany } from '@/api/ocrApi';
// import { useAppStore } from "@/store"
// log
import Logo from "@/layout/components/Sidebar/Logo.vue"
import { useDark, useToggle } from "@vueuse/core"
import { getBodyThemeBg } from "@/utils/index"
import classes from "./index.module.less"

interface PropsType {
	logoText?: string
	isViewBtn?: boolean
}
const emits = defineEmits(["handleViewChange","handleDownload"])
const viewval = ref<string>("1")
const viewData = [
	{ val: "1", text: "连页视图" },
	{ val: "2", text: "分页视图" },
]
const props = defineProps({
	ocrData: {
		type: String,
		default: "",
	},
	storageId: {
		type: String,
		default: "",
	},
	editorRef:{
		type: Object,
	}
})
// const appStore = useAppStore()
const handleViewSelect = (val: string) => {
	viewval.value = val
	emits("handleViewChange", val)
}
const handleSass = () => {
	window.open("http://orange.turntip.cn/doc")
}

const isDark = useDark({
	onChanged(dark: boolean) {
		// appStore.toggleTheme(dark)
	},
})
const toggleTheme = useToggle(isDark)
const handleToggleTheme = () => {
	toggleTheme()
}
// 下载
const handleDownload = () =>{
	emits("handleDownload")
}
////////////////////////////////////////////////  导入到知识库 ///////////////////
const route = useRoute();
const zxcId = ref<any>(route.query.id)
const dialog = reactive({
  title: '',
  visibleDialog: false,
  personList: [],
  isHaveBack: false,
  page: 1,
  size: 10,
  total: 0,
  item: { id: '' },
  // 树结构
  defaultProps: {
    children: 'children',
    label: 'realName',
    isLeaf: 'leaf'
  },
  treeLoading: false,
  expandedKeys: [0],
  treeRestoreList: [],
  treeRestorePathObj: { path: '', id: '' },
  realName: '',
});
const saveOption = ref('part')
// 导入到知识库
const onImpoon = async () =>{
	if (!props.ocrData) {
		Message.error('请先识别文档内容');
		return;
 	}
	getReset();
	dialog.visibleDialog = true;
	
}
// 关闭弹窗
const getClose = () =>{
	dialog.visibleDialog = false;
}
// 接收时重置
const getReset = () => {
  dialog.treeLoading = true;
  dialog.realName = '';
  let oParam = {
    sortDesc: 'type,create_time'
  };
  ApiPerSelectPersonalTree(oParam)
    .then((res) => {
      // console.log('🚀 ~ getReset ~ res:', res);

      dialog.treeRestorePathObj = res.data;
      dialog.treeRestoreList = res.data.children.filter((item) => item.type == 'folder');
      dialog.treeLoading = false;
    })
    .catch((err) => {
      dialog.treeLoading = false;
    });
};
//-选择树
const loadNode = (node, resolve) => {
  if (node.level == 0) {
    return resolve(node.data);
  }
  apiTreeFileSelectTree({
    parentId: node.key,
    sortDesc: 'type,create_time'
  }).then((res: any) => {
    // console.log('🚀 ~ loadNode ~ res:', res);

    let childrenArr = res.data.children.filter((item) => item.type == 'folder');
    return resolve(childrenArr);
  });
};
// 单击节点
const treeRestoreNodeClick = (data, node) => {
  dialog.treeRestorePathObj = data;
};

// 确定导入
const debounce_getComfirm = async () =>{
	if(!dialog.realName){
		Message.error('请输入文件名称');
		return;
	}
	if(!dialog.treeRestorePathObj.id){
		Message.error('请选择要导入的文件夹');
		return;
	}
	let params:any = {
		type: zxcId.value ? 'enterprise' : 'personal',
		content: outputMdTest(await props.editorRef.editorRef.saver.save()),
		treeNodeId: zxcId.value ? zxcId.value : dialog.treeRestorePathObj.id,
		realName: dialog.realName,
		storageId: props.storageId
	}
	if(zxcId.value){
		params.info = {type: saveOption.value }
	}
	let res:any = await apiOcrToLibrany(params);
	if(res.code == 200){
		Message.success('导入成功');
		dialog.visibleDialog = false;
		dialog.realName = '';
	}
	// dialog.visibleDialog = false;
	// 导入到知识库
	// console.log('🚀 ~ treeRestorePathObj.id:', dialog.treeRestorePathObj.id);
	// console.log('🚀 ~ dialog.realName:', dialog.realName);
}

</script>

<style lang="less" scoped>
.arco-dropdown-open .arco-icon-down {
	transform: rotate(180deg);
}
:deep(.arco-dropdown-option-icon) {
	display: flex;
	justify-content: center;
	align-items: center;
	line-height: 36px;
	width: 12px;
	height: 36px;
}
.path{
	padding: 15px;
}
.dialog-footer{
	display: inline-block;
	width: 100%;
	text-align: right;
}
.sidebar-logo-container{
	background-color: white !important;
}

</style>
